package com.platform.usercenter.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.platform.common.core.utils.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Http工具类
 *
 * @author cy
 * @date 2023/9/26
 */
public class HttpClientUtil {

    static final  int TIMEOUT_MSEC = 5 * 1000;

    public static void main(String[] args) {
         String token="YWMtkOt11qVREe6lFl_UPxzh4D0I4LsmqT9cvp89qr3mF-n34xsqHs9JH5BOxkREQf27AgMAAAGMr0u1tgAADi7Zp97mNVVyLUpUmDqZt3XuCgvX5yx2pXBYTr1Pqj0hAA";
        JSONObject obj=new JSONObject();
        obj.put("nickname", "王强");
        obj.put("avatarurl", "");

        String  res=null;//HttpClientUtil.pushPutForm("http://172.18.15.4:12000/easemob-demo/yzy/metadata/user/wangqiang",obj.toJSONString(),"Bearer "+token);
        System.out.println("res = " + res);
        /*String str="$2a$10$xIaSeDHwwvs.jJ8F6XAH2.WD6NlSBGnQmSi2VptUPfGrhr.GTrFXK";
        System.out.println("str = " + str.hashCode());
        List<String> list=new ArrayList<String>();
        list.add("1");
        list.add("2");
        list.add("3");
        list.add("4");
        list.add("5");
        list.add("6");
        List<String>  ss=list.subList(2*0,2*1);
        List<String>  ss1=list.subList(2*1,2*2);
         String url="https://im.yzy-gx.com:13000/easemob-demo/yzy/users";
         String tokenUrl="http://172.18.15.4:12000/easemob-demo/yzy/token";
        JSONObject objtoken=new JSONObject();
        objtoken.put("grant_type","client_credentials");
        objtoken.put("client_id","YXA6oIwNKsXaTUGiOdUTBhojvg");
        objtoken.put("client_secret","YXA6zKSnWf9Kca-VOGnMeXku9kxfl4M");
        objtoken.put("ttl",3600);
        JSONObject tokenres=JSONObject.parseObject(pushPost(tokenUrl,objtoken.toJSONString(),null));
        System.out.println(tokenres.getString("access_token"));

        JSONArray arr=new JSONArray();
        JSONObject obj=new JSONObject();
        obj.put("username","ceshiyzy1");
        obj.put("password","123456");
        obj.put("nickname","测试账号1");
        JSONObject obj1=new JSONObject();
        obj1.put("username","ceshiyzy2");
        obj1.put("password","123456");
        obj1.put("nickname","测试账号2");
        arr.add(obj);
        arr.add(obj1);*/
        //System.out.println(arr.toJSONString());
        //String res= pushPost(url,arr.toJSONString(),"Bearer eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VyX2tleSI6IjA4ZjRkNjM4LWQ3OGUtNDI1Ny05MzU4LWZjMzM5ZDIyMzM1YSIsInVzZXJuYW1lIjoiYWRtaW4ifQ.QvTX9terXqFzQORemB9rQJRP9ErqX9JgwrYSw_M0J5CNw3Vre7o9GAt5n6L8eBuorGRSJiqVW8dKUChA7jUMgQ");
        //System.out.println(res);

    }
    public static RequestConfig requestConfig=null;
    static {
                 requestConfig = RequestConfig.custom()
                .setConnectTimeout(3000) // 设置连接超时时间
                .setConnectionRequestTimeout(3000) // 设置请求超时时间
                .setSocketTimeout(3000) // 设置数据读取超时时间
                .build();
    }

    /**
     * 发送GET方式请求
     * @param url
     * @param paramMap
     * @return
     */
    public static String doGet(String url,Map<String,String> paramMap){
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        String result = "";
        CloseableHttpResponse response = null;

        try{
            URIBuilder builder = new URIBuilder(url);
            if(paramMap != null){
                for (String key : paramMap.keySet()) {
                    builder.addParameter(key,paramMap.get(key));
                }
            }
            URI uri = builder.build();

            //创建GET请求
            HttpGet httpGet = new HttpGet(uri);

            //发送请求
            response = httpClient.execute(httpGet);

            //判断响应状态
            if(response.getStatusLine().getStatusCode() == 200){
                result = EntityUtils.toString(response.getEntity(),"UTF-8");
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                response.close();
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return result;
    }

    /**
     * 发送POST方式请求
     * @param url
     * @param paramMap
     * @return
     * @throws IOException
     */
    public static String doPost(String url, Map<String, String> paramMap) throws IOException {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";

        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);

            // 创建参数列表
            if (paramMap != null) {
                List<NameValuePair> paramList = new ArrayList();
                for (Map.Entry<String, String> param : paramMap.entrySet()) {
                    paramList.add(new BasicNameValuePair(param.getKey(), param.getValue()));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
                httpPost.setEntity(entity);
            }

            httpPost.setConfig(builderRequestConfig());

            // 执行http请求
            response = httpClient.execute(httpPost);

            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (Exception e) {
            throw e;
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return resultString;
    }

    /**
     * 发送POST方式请求
     * @param url
     * @param paramMap
     * @return
     * @throws IOException
     */
    public static String doPost4Json(String url, Map<String, String> paramMap) throws IOException {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";

        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);

            if (paramMap != null) {
                //构造json格式数据
                JSONObject jsonObject = new JSONObject();
                for (Map.Entry<String, String> param : paramMap.entrySet()) {
                    jsonObject.put(param.getKey(),param.getValue());
                }
                StringEntity entity = new StringEntity(jsonObject.toString(),"utf-8");
                //设置请求编码
                entity.setContentEncoding("utf-8");
                //设置数据类型
                entity.setContentType("application/json");
                httpPost.setEntity(entity);
            }

            httpPost.setConfig(builderRequestConfig());

            // 执行http请求
            response = httpClient.execute(httpPost);

            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (Exception e) {
            throw e;
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return resultString;
    }
    private static RequestConfig builderRequestConfig() {
        return RequestConfig.custom()
                .setConnectTimeout(TIMEOUT_MSEC)
                .setConnectionRequestTimeout(TIMEOUT_MSEC)
                .setSocketTimeout(TIMEOUT_MSEC).build();
    }


    //post请求
    public  static String pushPostLogin(String url, String postData) {
        String result = null;
        HttpPost post = null;
        try {
            HttpClient client = HttpClientBuilder.create().build();
            post = new HttpPost(url);
            post.setHeader(HTTP.CONTENT_TYPE, "application/json; charset=UTF-8");
            post.setHeader("Accept", "application/json; charset=UTF-8");
            if(StringUtils.isNotEmpty(postData)){
                StringEntity entity = new StringEntity(postData, "UTF-8");
                post.setEntity(entity);
            }
            HttpResponse response = client.execute(post);
            result = EntityUtils.toString(response.getEntity(), "UTF-8");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (post != null) {
                post.releaseConnection();
            }
        }
        return null;
    }

    public static String pushPut(String url, String postData,String accessToken){
        String result = null;
        HttpPut put = null;
        try {
            HttpClient client = HttpClientBuilder.create().build();
            System.out.println("请求地址："+url);
            put = new HttpPut(url);
            put.setConfig(requestConfig);
            put.setHeader(HTTP.CONTENT_TYPE, "application/json");
            put.setHeader("Accept", "application/json");
            put.setHeader("Authorization", accessToken);
            StringEntity entity = new StringEntity(postData, "UTF-8");
            put.setEntity(entity);
            HttpResponse response = client.execute(put);
            result = EntityUtils.toString(response.getEntity(), "UTF-8");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (put != null) {
                put.releaseConnection();
            }
        }
        return null;
    }

    public static String pushPutForm(String url, Map<String, String> params,String accessToken){
        String result = null;
        HttpPut put = null;
        try {
            HttpClient client = HttpClientBuilder.create().build();
            System.out.println("请求地址："+url);
            put = new HttpPut(url);
            put.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
            put.setHeader("Authorization", accessToken);
            if (params != null && !params.isEmpty()) {
                List<NameValuePair> formParams = new ArrayList<NameValuePair>(); // 构建POST请求的表单参数
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
                if(formParams != null && formParams.size() > 0){
                    put.setEntity(new UrlEncodedFormEntity(formParams, "UTF-8"));
                }
            }
            HttpResponse response = client.execute(put);
            result = EntityUtils.toString(response.getEntity(), "UTF-8");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (put != null) {
                put.releaseConnection();
            }
        }
        return null;
    }
    //post请求
    public  static String pushPost(String url, String postData,String accessToken) {
        String result = null;
        HttpPost post = null;
        try {
            HttpClient client = HttpClientBuilder.create().build();
            System.out.println("请求地址："+url);
            post = new HttpPost(url);
            post.setConfig(requestConfig);
            post.setHeader(HTTP.CONTENT_TYPE, "application/json");
            post.setHeader("Accept", "application/json");
            post.setHeader("Authorization", accessToken);
            StringEntity entity = new StringEntity(postData, "UTF-8");
            post.setEntity(entity);
            HttpResponse response = client.execute(post);
            result = EntityUtils.toString(response.getEntity(), "UTF-8");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (post != null) {
                post.releaseConnection();
            }
        }
        return null;
    }
    //post请求
    public  static String pushGet(String url, String getData,String accessToken) {
        String result = null;
        HttpGet get = null;
        try {
            HttpClient client = HttpClientBuilder.create().build();
            get = new HttpGet(url);
            get.setHeader(HTTP.CONTENT_TYPE, "application/json; charset=UTF-8");
            get.setHeader("Accept", "application/json; charset=UTF-8");
            get.setHeader("Authorization", accessToken);
//            StringEntity entity = new StringEntity(getData, "UTF-8");
//            get.setEntity(entity);
            HttpResponse response = client.execute(get);
            result = EntityUtils.toString(response.getEntity(), "UTF-8");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (get != null) {
                get.releaseConnection();
            }
        }
        return null;
    }


    public static String pushDelete(String url,String accessToken){
        String result = null;
        HttpDelete delet = null;
        try {
            HttpClient client = HttpClientBuilder.create().build();
            System.out.println("请求地址："+url);
            delet= new HttpDelete(url);
            delet.setHeader(HTTP.CONTENT_TYPE, "application/json");
            delet.setHeader("Authorization", accessToken);
            HttpResponse response = client.execute(delet);
            result = EntityUtils.toString(response.getEntity(), "UTF-8");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (delet != null) {
                delet.releaseConnection();
            }
        }
        return null;
    }

}
